/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-6-11 下午2:56 Created by dwzhang
 */
package com.xunton.bss.weixin.api.component;

import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import com.xunton.bss.weixin.api.WeixinException;
import com.xunton.bss.weixin.api.component.event.UnauthorizedEvent;
import com.xunton.bss.weixin.api.component.event.VerifyTicketEvent;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 第三方平台事件处理器。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a> 
 * @version 1.0 15-6-11 下午2:56
 */
public class CompEventHandler
{
    private Log log = LogFactory.getLog(CompEventHandler.class);
    private ComponentAgent agent;
    private ComponentListener listener;

    public void setAgent(ComponentAgent agent)
    {
        this.agent = agent;
    }

    public ComponentListener getListener()
    {
        return listener;
    }

    public void setListener(ComponentListener listener)
    {
        this.listener = listener;
    }

    public <E extends ComponentEvent> E parse(String xml)
            throws WeixinException
    {
        ComponentEvent event = null;
        if (StringUtils.indexOfIgnoreCase(xml, "component_verify_ticket") > 0) {
            event = parse(xml, VerifyTicketEvent.class);

        }
        else if (StringUtils.indexOfIgnoreCase(xml, "unauthorized") > 0) {
            event = parse(xml, UnauthorizedEvent.class);
        }
        else {
            log.warn("Invalid event:" + xml);
        }
        return (E) event;
    }

    public void handleEvent(ComponentEvent event)
            throws WeixinException
    {
        if (event instanceof VerifyTicketEvent) {
            log.info(
                    "Set component ticket to " + ((VerifyTicketEvent) event).getTicket() + " for app " + event.getAppId());
            agent.setVerifyTicket(event.getAppId(), ((VerifyTicketEvent) event).getTicket());
        }
        else if (event instanceof UnauthorizedEvent) {
            log.info(
                    "Unauthorize the app " + ((UnauthorizedEvent) event).getAuthorizerAppid() + " for component " + event.getAppId());
            if (listener != null) {
                listener.onEvent((UnauthorizedEvent) event);
            }
        }
    }

    protected  <E extends ComponentEvent> E parse(String xmlStr, Class classz)
            throws WeixinException
    {
        try {
            JAXBContext context = JAXBContext.newInstance(classz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader reader = new StringReader(xmlStr);
            return (E) unmarshaller.unmarshal(reader);
        }
        catch (Exception e) {
            throw new WeixinException("err.bss.weixin.component.parse_xml", e.getMessage());
        }
    }
}
